package com.inossem.warehousestorage_inossem.activity.in_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.in_storage.extra.InStorageExtra;
import com.inossem.warehousestorage_inossem.bean.inStorage.InStorageAllocatingOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.List;

/**
 * 作者：wsy on 2017/12/2 11:26
 * <p>
 * 邮箱：445979770@qq.com
 */

public class InStorageAllocatingMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_EDITTEXT = "1";

    private static final String TYPE_DATEPICKER = "2";

    private static final String TYPE_SELECT = "3";

    private static final String REQUIRED_NO = "0";

    private static final String REQUIRED_YES = "1";

    private static final String TYPE_SERIAL = "serial";

    private static final String TYPE_INDEX = "index";

    private TextView title, serialNumber, materielCode, materielDescription, inStorageNumber, sendFatory, sendLocation, pageInfo, showAndHide;

//    private EditText inStorageNumber;

    private Button previous, next;

    private String id, unit, mMaterielCode;

    private int index;

    private InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean materielItem;

    private PercentLinearLayout batchLayout;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_in_storage_allocating_materiel_detail);
        initView(InStorageAllocatingMaterielDetailActivity.this);
        initData(InStorageAllocatingMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        sendFatory = (TextView) activity.findViewById(R.id.sendFatory);
        sendLocation = (TextView) activity.findViewById(R.id.sendLocation);
        inStorageNumber = (TextView) activity.findViewById(R.id.inStorageNumber);
//        factory = (TextView) activity.findViewById(R.id.factory);
//        demandCompany = (TextView) activity.findViewById(R.id.demandCompany);
//        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
//        costObject = (TextView) activity.findViewById(R.id.costObject);
//        objectDescription = (TextView) activity.findViewById(R.id.objectDescription);
        pageInfo = (TextView) activity.findViewById(R.id.pageInfo);
        showAndHide = (TextView) activity.findViewById(R.id.showAndHide);
        previous = (Button) activity.findViewById(R.id.previous);
        next = (Button) activity.findViewById(R.id.next);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, R.string.activity_receive_receive_item_title_short, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate(activity);
            }
        });
//        inventoryAddress.setOnClickListener(new NoDoubleClickListener() {
//            @Override
//            public void onNoDoubleClick(View v) {
//                DialogUtils.getReceiveInventoryAddressDialog(activity, InStorageUtils.getReceiveInventoryAddressList(activity), new DialogUtils.ReceiveInventoryAddressListener() {
//                    @Override
//                    public void onSelect(Dialog dialog, String inventoryAddressValue, String inventoryAddressCode, String factoryValue, String factoryCode) {
//                        inventoryAddress.setText(inventoryAddressCode + " - " + inventoryAddressValue);
//                    }
//                }).show();
//            }
//        });
//        inStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
//            if (hasFocus) {
//                inStorageNumber.setText("");
//            }
//        });
        previous.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index > 0) {
                    index--;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index < (InStorageUtils.getAllocatingMaterielListSize(activity) - 1)) {
                    index++;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        showAndHide.setOnClickListener((View v) -> {
            if (batchLayout.getVisibility() == View.GONE) {
                batchLayout.setVisibility(View.VISIBLE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_hide_information));
            } else if (batchLayout.getVisibility() == View.VISIBLE) {
                batchLayout.setVisibility(View.GONE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_show_information));
            }
        });
        getExtra(activity);
        getIndexBySerial(activity, id);
        getData(activity, TYPE_SERIAL);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            int indexTemp = InStorageUtils.getAllocatingIndexByMaterielCode(activity, mMaterielCode);
            if (indexTemp != -1 && indexTemp != index) {
                index = indexTemp;
                changeAndUpdate(activity);
            }
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        id = activity.getIntent().getStringExtra(InStorageExtra.ID);
    }

    private void getIndexBySerial(Context context, String serialNumber) {
        index = InStorageUtils.getAllocatingIndexByMaterielCode(context, serialNumber);
    }

    private void getData(BaseActivity context, String getMaterielInformationFromType) {
        switch (getMaterielInformationFromType) {
            case TYPE_SERIAL:
                materielItem = InStorageUtils.getAllocatingMaterielInformationBySerial(context, id);
                break;
            case TYPE_INDEX:
                materielItem = InStorageUtils.getAllocatingMaterielInformationByIndex(context, index);
                break;
        }
        unit = materielItem.getName_zh();
        serialNumber.setText(materielItem.getStock_input_rid());
        materielCode.setText(materielItem.getMat_code());
        materielDescription.setText(materielItem.getMat_name());
        inStorageNumber.setText(materielItem.getQty() + unit);
        sendFatory.setText(materielItem.getFty_output_code() + "-" + materielItem.getFty_output_name());
        sendLocation.setText(materielItem.getLocation_output_code() + "-" + materielItem.getLocation_output_name());
//        factory.setText(materielItem.getFactoryCode() + " - " + materielItem.getFactoryValue());
//        demandCompany.setText(materielItem.getDemandCompany());
//        inventoryAddress.setText(materielItem.getInventoryAddressCode() + " - " + materielItem.getInventoryAddressValue());
//        costObject.setText(materielItem.getCostObject());
//        objectDescription.setText(materielItem.getObjectDescription());
        batchLayout.removeAllViews();
        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean> batchList = materielItem.getBatch_material_spec_list();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean batchItem = batchList.get(i);
            String type = batchItem.getBatch_spec_type();
            boolean required = REQUIRED_YES.equals(batchItem.getRequired()) ? true : false;
            switch (type) {
                case TYPE_EDITTEXT:
                    InStorageUtils.createEditText(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), i + 1);
                    break;
                case TYPE_DATEPICKER:
                    InStorageUtils.createDatePicker(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), i + 1);
                    break;
                case TYPE_SELECT:
                    InStorageUtils.createAllocatingSelect(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), batchItem.getInfo(), i + 1);
                    break;
            }
        }
        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean> batchSpecListBeans = materielItem.getBatch_spec_list();
        if (batchSpecListBeans.size() != 0) {
            InStorageUtils.creatHorizontalView(context , batchLayout);
        }
        for (int i = 0; i < batchSpecListBeans.size(); i++) {
           InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean batchItem = batchSpecListBeans.get(i);
            String type = batchItem.getBatch_spec_type();
            boolean required = REQUIRED_YES.equals(batchItem.getRequired()) ? true : false;
            switch (type) {
                case TYPE_EDITTEXT:
                    InStorageUtils.createEditText(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), batchList.size() + i + 1);
                    break;
                case TYPE_DATEPICKER:
                    InStorageUtils.createDatePicker(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), batchList.size() + i + 1);
                    break;
                case TYPE_SELECT:
                    InStorageUtils.createAllocatingSelect(context, batchLayout, batchItem.getBatch_spec_name(), required, batchItem.getText(), batchItem.getBatch_spec_value(), batchItem.getInfo(), batchList.size() + i + 1);
                    break;
            }
        }
        pageInfo.setText(InStorageUtils.getAllocatingMaterielListSize(context) + " | " + (index + 1));
        if (index <= 0) {
            previous.setText(R.string.activity_receive_result_back);
        } else {
            previous.setText(R.string.activity_in_storage_receive_materiel_detail_previous);
        }
        if (index >= (InStorageUtils.getAllocatingMaterielListSize(context) - 1)) {
            next.setText(R.string.activity_receive_result_back);
        } else {
            next.setText(R.string.activity_in_storage_receive_materiel_detail_next);
        }
    }

    private void updateInfo(Context context) {
//        materielItem.setRealInStorageNumber(inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim());
//        String[] inventoryAddressArray = inventoryAddress.getText().toString().split(" - ");
//        materielItem.setInventoryAddressCode(inventoryAddressArray[0]);
//        materielItem.setInventoryAddressValue(inventoryAddressArray[1]);
        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean> batchList = materielItem.getBatch_material_spec_list();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean batchItem = batchList.get(i);
            String type = batchItem.getBatch_spec_type();
            View view = findViewById(i + 1);
            switch (type) {
                case TYPE_EDITTEXT:
                    batchItem.setText(((EditText) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_DATEPICKER:
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_SELECT:
                    batchItem.setBatch_spec_value(((TextView) view.findViewById(R.id.value)).getText().toString());
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
            }
        }
        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean> batchSpecListBeans = materielItem.getBatch_spec_list();
        for (int i = 0; i < batchSpecListBeans.size(); i++) {
            InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean batchItem = batchSpecListBeans.get(i);
            String type = batchItem.getBatch_spec_type();
            View view = findViewById(batchList.size() + i + 1);
            switch (type) {
                case TYPE_EDITTEXT:
                    batchItem.setText(((EditText) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_DATEPICKER:
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_SELECT:
                    batchItem.setBatch_spec_value(((TextView) view.findViewById(R.id.value)).getText().toString());
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
            }
        }
        InStorageUtils.updateAllocatingInStorageItem(context, materielItem);
    }

    private String check(Context context) {
//        String inStorageNumberStr = inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim();
//        if (TextUtils.isEmpty(inStorageNumberStr)) {
//            return "入库数量不可以为空";
//        }
//
//        if (!RegexUtils.checkDecimal(inStorageNumberStr)) {
//            return "入库数量非法";
//        }
//
//        if (RegexUtils.checkZero(inStorageNumberStr)) {
//            return "入库数量必须大于0";
//        }
//
//        float maxNumber = Float.parseFloat(materielItem.getInStorageNumber());
//        float inStoragetNumberFloat = Float.parseFloat(inStorageNumberStr);
//        if (inStoragetNumberFloat > maxNumber) {
//            return "入库数量不能大于验收入库单据中的入库数量";
//        }

        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean> batchList = materielItem.getBatch_material_spec_list();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchMaterialSpecListBean batchItem = batchList.get(i);
            String name = batchItem.getBatch_spec_name();
            String type = batchItem.getBatch_spec_type();
            String required = batchItem.getRequired();
            if (REQUIRED_YES.equals(required)) {
                View view = findViewById(i + 1);
                if (TYPE_EDITTEXT.equals(type)) {
                    EditText textEditText = (EditText) view.findViewById(R.id.text);
                    if (TextUtils.isEmpty(textEditText.getText().toString())) {
                        return name + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                } else {
                    TextView textTextView = (TextView) view.findViewById(R.id.text);
                    if (TextUtils.isEmpty(textTextView.getText().toString())) {
                        return name + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                }
            }
        }
        List<InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean> batchSpecListBeans = materielItem.getBatch_spec_list();
        for (int i = 0; i < batchSpecListBeans.size(); i++) {
            InStorageAllocatingOverviewBean.ReceiveInAllocatingStorageListBean.StockInputItemBean.BatchSpecListBean batchItem = batchSpecListBeans.get(i);
            String name = batchItem.getBatch_spec_name();
            String type = batchItem.getBatch_spec_type();
            String required = batchItem.getRequired();
            if (REQUIRED_YES.equals(required)) {
                View view = findViewById(batchList.size() + i + 1);
                if (TYPE_EDITTEXT.equals(type)) {
                    EditText textEditText = (EditText) view.findViewById(R.id.text);
                    if (TextUtils.isEmpty(textEditText.getText().toString())) {
                        return name + context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                } else {
                    TextView textTextView = (TextView) view.findViewById(R.id.text);
                    if ("".equals(textTextView.getText().toString())) {
                        return name + context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                }
            }
        }
        return null;
    }

    private void backAndUpdate(Context context) {
        String checkResult = check(context);
        if (checkResult == null) {
            updateInfo(context);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_exit), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    InStorageAllocatingMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void changeAndUpdate(BaseActivity activity) {
        String checkResult = check(activity);
        if (checkResult == null) {
            updateInfo(activity);
            getData(activity, TYPE_INDEX);
        } else {
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    getData(activity, TYPE_INDEX);
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate(InStorageAllocatingMaterielDetailActivity.this);
    }
}
